#!/bin/bash

set -e
PID=$$
PGID=${PGID:=$PID}

# Kills all child processes in this script's same process group
# if a signal happens or if this script exits for any reason.
trap 'set +e ; trap "" SIGTERM ; kill -- -$PGID ; trap - SIGHUP SIGINT SIGTERM EXIT ; exit' SIGHUP SIGINT SIGTERM EXIT

function get_script_location()    # https://stackoverflow.com/a/246128
{
    SOURCE="${BASH_SOURCE[0]}"
    while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
      DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
      # Note symlinks will fail on macOS due to missing readlink command
      SOURCE="$(readlink "$SOURCE")"
      [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
    done
    DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
    echo $DIR
}

DIR=$(get_script_location)
DIR="$DIR/.."

MAPD_TCP_PORT=${MAPD_TCP_PORT:=6274}
MAPD_HTTP_PORT=${MAPD_HTTP_PORT:=6278}
MAPD_WEB_PORT=${MAPD_WEB_PORT:=6273}
MAPD_CALCITE_PORT=${MAPD_CALCITE_PORT:=6279}

MAPD_DATA=${MAPD_DATA:="data"}

while (( $# )); do
    case "$1" in
        --read-only)
            RO="--read-only" ;;
        --base-port)
            shift
            MAPD_WEB_PORT=$1
            MAPD_TCP_PORT=$(($MAPD_WEB_PORT-1))
            MAPD_HTTP_PORT=$(($MAPD_WEB_PORT-2))
            MAPD_CALCITE_PORT=$(($MAPD_WEB_PORT+1))
            ;;
        --data)
            shift
            MAPD_DATA=$1
            ;;
        --enable-https)
            HTTPS="--enable-https" ;;
        --cert)
            shift
            HTTPS_CERT="--cert $1" ;;
        --key)
            shift
            HTTPS_KEY="--key $1" ;;
        --config)
            shift
            if [ -e "$1" ]; then
                CONFIG_FILE="$1"
                CONFIG="--config $1"
            else
                echo "WARN: config file does not exist, ignoring: --config $1" >&2
            fi
            ;;
        --non-interactive)
            NON_INTERACTIVE=true ;;
        --disable-open-frontend)
            DISABLE_OPEN_FRONTEND=true ;;
        --verbose)
            VERBOSE="--verbose" ;;
        *)
            break ;;
    esac
    shift
done

echo "Backend TCP:  localhost:${MAPD_TCP_PORT}"
echo "Backend HTTP: localhost:${MAPD_HTTP_PORT}"
echo "Frontend Web: localhost:${MAPD_WEB_PORT}"
echo "Calcite TCP:  localhost:${MAPD_CALCITE_PORT}"

if [ ! -d $MAPD_DATA/mapd_data ]; then
    mkdir -p $MAPD_DATA
    ./bin/initdb -f --data $MAPD_DATA

    if [ ! "$NON_INTERACTIVE" = true ]; then
        echo "Download and insert sample data? Y/n"
        read choice
        if [ -z "$choice" ]; then choice="Y"; fi
        case $choice in
            [yY]* )
                INSERT_SAMPLE_DATA=true;;
        esac
    fi
fi

VMAJOR=${BASH_VERSINFO[0]}
VMINOR=${BASH_VERSINFO[1]}
if [[ $VMAJOR -eq 4 && $VMINOR -le 3 || $VMAJOR -lt 4 ]]; then    # Bash 4.3 and older (CentOS)
    LEGACY=1
else
    unset LEGACY
fi

./bin/omnisci_server $MAPD_DATA $RO --port $MAPD_TCP_PORT --http-port $MAPD_HTTP_PORT --calcite-port $MAPD_CALCITE_PORT $CONFIG $VERBOSE $* &
PID1=$!
echo "- omnisci_server $PID1 started"

if [ "$INSERT_SAMPLE_DATA" = true ] && [ ! "$NON_INTERACTIVE" = true ]; then
    echo "- waiting 5s before inserting sample data"
    sleep 5
    . "$DIR/insert_sample_data"
fi

if [ -d frontend ] && [ -e ./bin/omnisci_web_server ]; then
    # use https for backend-url if both ssl-cert and ssl-key options are in the config file
    BACKEND_URL="--backend-url http://localhost:${MAPD_HTTP_PORT}"
    if [ -e "$CONFIG_FILE" ]; then
        if grep --quiet "^ssl-cert" "$CONFIG_FILE" && grep --quiet "^ssl-private-key" "$CONFIG_FILE"; then
            BACKEND_URL="--backend-url https://localhost:${MAPD_HTTP_PORT}"
        fi
        # always use backend-url from the config file
        if grep --quiet "^backend-url" "$CONFIG_FILE"; then
            BACKEND_URL=""
        fi
    fi
    ./bin/omnisci_web_server $RO --port $MAPD_WEB_PORT ${BACKEND_URL} --data $MAPD_DATA $HTTPS $HTTPS_CERT $HTTPS_KEY $CONFIG $VERBOSE &
    PID2=$!
    echo "- omnisci_web_server $PID2 started"

    if [ ! "$DISABLE_OPEN_FRONTEND" = true ]; then
        if [ ! -z "$HTTPS" ] ; then
            MAPDFRONTEND="https://localhost:${MAPD_WEB_PORT}"
        else
            MAPDFRONTEND="http://localhost:${MAPD_WEB_PORT}"
        fi
        sleep 5
        if hash open 2>/dev/null; then
            open "$MAPDFRONTEND" 2> /dev/null || true
        elif hash xdg-open 2>/dev/null; then
            xdg-open "$MAPDFRONTEND" 2> /dev/null || true
        else
            echo "Navigate to: $MAPDFRONTEND"
        fi
    else
        echo "Navigate to: $MAPDFRONTEND"
    fi
fi

if [ "$LEGACY" = "" ]; then
  wait -n
else
  wait $PID1
fi
